import React, { Component } from 'react';
import { Input, DatePicker, Button, Tabs } from 'antd';
import { Table, Space, Modal, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom'
import './Dingdanliebiao.css'
import axios from 'axios'
import qs from 'qs'
const { confirm } = Modal;
class Dingdanliebiao extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time1: '',
      time2: '',
      id: '',
      sname: '',
      pname: '',
      userLoginName: 'shop01',
      dinDanList: [],
      showList: [],
      daifukuan: [],
      daichuku: [],
      yichuku: [],
      yiwancheng: [],
      yiquxiao: [],
      shouhouzhong: [],
    }
  }
  //获取数据
  getData(first, userLoginName, arr, status) {
    if (status) {
      var data = qs.stringify({ userLoginName: userLoginName, status: status })
    } else {
      var data = qs.stringify({ userLoginName: userLoginName })
    }
    return new Promise((resolve, reject) => {
      axios.post(
        "api/backstage/shop/findAllOrderList",
        data,
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
          },
        }
      ).then((res) => {
        if (res.data.code === 200) {
          var newarr = arr
          var list = res.data.data
          list = this.shengXuArr(list);
          //扁平数据变树形数据
          var TreeData = this.GetTreeData(list);
          list = TreeData;
          this.shujuchuli(list);
          if (first) {
            this.setState({
              [newarr]: list,
              showList: list
            })
          } else {
            this.setState({
              [newarr]: list,
            })
          }
        }
      });
    })

  }
  componentWillMount() {
    if (sessionStorage.getItem("userlist")) {
      this.setState({
        serLoginName: JSON.parse(sessionStorage.getItem("userlist"))[0]
      })
    }
    this.getData(true, this.state.userLoginName, 'dinDanList')
    this.getData(false, this.state.userLoginName, 'daifukuan', 1)
    this.getData(false, this.state.userLoginName, 'daichuku', 2)
    this.getData(false, this.state.userLoginName, 'yichuku', 3)
    this.getData(false, this.state.userLoginName, 'yiwancheng', 4)
    this.getData(false, this.state.userLoginName, 'yiquxiao', 5)
    this.getData(false, this.state.userLoginName, 'shouhouzhong', 5)
  }
  //数组升序排列
  shengXuArr(data) {
    var t = 0;
    for (var i = 0; i < data.length - 1; i++) {
      for (var j = 0; j < data.length - i - 1; j++) {
        if (data[j].orderNumber > data[j + 1].orderNumber) {
          t = data[j + 1];
          data[j + 1] = data[j];
          data[j] = t;
        }
      }
    }
    return data;
  }
  //输入框输入
  inputChange(key, event) {
    this.setState({
      [key]: event.target.value
    }, () => {
    })
  }
  //日期选择
  timeChange(date, dataString) {
    this.setState({
      time1: dataString[0],
      time2: dataString[1]
    })
  }
  // tab栏切换
  callback = (key) => {
    if (key === '1') {
      this.setState({
        showList: this.state.dinDanList
      })
    } else if (key === '2') {
      this.setState({
        showList: this.state.daifukuan
      })
    } else if (key === '3') {
      this.setState({
        showList: this.state.daichuku
      })
    } else if (key === '4') {
      this.setState({
        showList: this.state.yichuku
      })
    } else if (key === '5') {
      this.setState({
        showList: this.state.yiwancheng
      })
    }
    else if (key === '6') {
      this.setState({
        showList: this.state.yiquxiao
      })
    }
    else if (key === 7) {
      this.setState({
        showList: this.state.shouhouzhong
      })
    }
  }
  //扁平数据处理
  GetTreeData(data) {
    var TreeData = [];
    var map = new Map(); //存在id,对应所在的内存地址
    var outputObj, orderNumber;
    for (var i = 0; i < data.length; i++) {
      orderNumber = data[i].orderNumber;
      if (map.has(orderNumber)) {
        //存在，将些信息，加入到对应id=pid的对象上的children
        if (!map.get(orderNumber).childrens)
          map.get(orderNumber).childrens = [];
        var obj = new Object(data[i]);
        map.get(orderNumber).childrens.push(obj);
        map.set(data[i].orderNumber, obj);
      } else if (!map.has(orderNumber)) {
        //这里处理pid不存在，pid不存在，程序不考虑这种情况
        outputObj = new Object(data[i]);
        TreeData.push(outputObj);
        map.set(data[i].orderNumber, outputObj);
        if (!map.get(orderNumber).childrens)
          map.get(orderNumber).childrens = [];
        var obj1 = new Object(data[i]);
        map.get(orderNumber).childrens.push(obj1);
        map.set(data[i].orderNumber, obj1);
      }
    }
    return TreeData;
  }
  //特殊字段增加(总金额、物流+运单号)
  shujuchuli(data) {
    let jine = 0;
    let priceAndNum = "";
    let wuLiuInfo = "";
    let danState = "";
    for (let i of data) {
      for (let j of i.childrens) {
        if (j.orderApply >= 1) {
          danState = "售后中";
        } else {
          if (j.orderStatus === 0) {
            danState = "待付款";
          } else if (j.orderSendStatus === 0 || i.orderSendStatus === 1) {
            danState = "待出库";
          } else if (j.orderSendStatus === 2) {
            danState = "已出库";
          } else if (j.orderSendStatus === 3) {
            danState = "已完成";
          } else if (j.orderIsCancel === 1) {
            danState = "已取消";
          }
        }
        j.danState = danState;
        jine += j.goodsRealPrice * j.goodsNumber;
        priceAndNum = "￥" + j.goodsRealPrice + ".00 / " + j.goodsNumber;
        j.priceAndNum = priceAndNum;
        priceAndNum = "";
      }
      wuLiuInfo = i.orderCourier + " / " + i.orderCourierId;
      i.wuLiuInfo = wuLiuInfo;
      i.jine = "￥" + jine + ".00";
      jine = 0;
      wuLiuInfo = "";
    }
  }
  //查询
  search() {
    let data = {};
    if (this.state.id !== '') data['orderNumber'] = this.state.id;
    if (this.state.userLoginName !== '') data['userLoginName'] = this.state.userLoginName;
    if (this.state.sname !== '') data['goodsName'] = this.state.sname;
    if (this.state.pname !== '') data['username'] = this.state.pname;
    if (this.state.time1 !== '') data['startTime'] = this.state.time1;
    if (this.state.time2 !== '') data['endTime'] = this.state.time2;
    axios.post("api/backstage/shop/findAllOrderList", qs.stringify(data), {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
      },
    })
      .then((res) => {
        if (res.data.code === 200) {
          message
            .loading('查询中..', 1)
            .then(() => {
              message.success(' 查询成功', 2.5)
              let list = [];
              list = res.data.data;
              list = this.shengXuArr(list);
              //扁平数据变树形数据
              var TreeData = this.GetTreeData(list);
              list = TreeData;
              this.shujuchuli(list);
              this.setState({
                showList: list
              })
            })
        } else {
          message
            .loading('查询中..', 1)
            .then(() => {
              message.warning('无数据', 2.5)
            })
        }
      }).catch(err => {
        message
          .loading('查询中..', 1)
          .then(() => {
            message.error('数据库错误', 2.5)
          })
      })
  }
  //重置
  reset() {
    this.setState({
      time1: '',
      time2: '',
      id: '',
      sname: '',
      pname: '',
      showList: this.state.dinDanList
    })
  }
  //退款
  tuikuan(data) {
    confirm({
      title: '是否同意退款?',
      icon: <ExclamationCircleOutlined />,
      okText: '同意',
      cancelText: '取消',
      onOk() {
        axios.post(
          "api/backstage/shop/notAgreeApply",
          qs.stringify({ orderNumber: data.orderNumber, reason: '' }),
          {
            headers: {
              "Content-Type":
                "application/x-www-form-urlencoded;charset=utf-8",
            },
          }
        )
          .then((res) => {
            message.success('已同意');
          });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  gochu() {
    this.props.history.push('/chuku')
  }
  render() {

    const { RangePicker } = DatePicker;
    const { TabPane } = Tabs;
    const { Column, ColumnGroup } = Table;
    const paginationProps = {
      pageSize: 5
    }
    return (
      <>
        <div className='content'>
          <div className='header'>
            <div className='left'>
              <div>
                <span>订单编号:</span>
                <span>
                  <Input placeholder="请输入订单编号"
                    value={this.state.id}
                    onChange={this.inputChange.bind(this, 'id')} />
                </span>
              </div>
              <div>
                <span>商品名称:</span>
                <span>
                  <Input placeholder="请输入商品名称"
                    value={this.state.sname}
                    onChange={this.inputChange.bind(this, 'sname')} />
                </span>
              </div>
              <div>
                <span>买家名:</span>
                <span>
                  <Input placeholder="请输入买家名"
                    value={this.state.pname}
                    onChange={this.inputChange.bind(this, 'pname')} />
                </span>
              </div>
              <div>
                <span>下单时间:</span>
                <span>
                  <RangePicker
                    onChange={this.timeChange.bind(this)} />
                </span>
              </div>
            </div>
            <div className='right'>
              <Button type="primary"
                onClick={this.search.bind(this)}
                danger>
                查询
              </Button>
              <Button onClick={this.reset.bind(this)} >
                重置
              </Button>
            </div>
          </div>
          <div className='nr'>
            <Tabs defaultActiveKey="1" onChange={this.callback}>
              <TabPane tab={'全部(' + this.state.dinDanList.length + ')'} key="1"> </TabPane>
              <TabPane tab={'待付款(' + this.state.daifukuan.length + ')'} key="2"> </TabPane>
              <TabPane tab={'待出库(' + this.state.daichuku.length + ')'} key="3"> </TabPane>
              <TabPane tab={'已出库(' + this.state.yichuku.length + ')'} key="4"> </TabPane>
              <TabPane tab={'已完成(' + this.state.yiwancheng.length + ')'} key="5"> </TabPane>
              <TabPane tab={'已取消(' + this.state.yiquxiao.length + ')'} key="6"> </TabPane>
              <TabPane tab={'售后中(' + this.state.shouhouzhong.length + ')'} key="7"> </TabPane>
            </Tabs>
            <Table
              dataSource={this.state.showList}
              key='qwer'
              bordered={true}
              pagination={paginationProps}>
              <Column title="订单号" dataIndex="orderNumber" key="orderNumber" align='center' />
              <Column title="下单时间" dataIndex="orderTime" key="orderTime" align='center' />
              <ColumnGroup title="商品信息" key='xx'>
                <Column title="名称" dataIndex="goodsName" key="goodsName" align='center'
                  render={(text, record) => (
                    <Space size="middle" key='xq'>
                      <a key='ww'>{text}</a>
                    </Space>
                  )} />
                <Column title="单价/数量" dataIndex="priceAndNum" key="priceAndNum" align='center' />
              </ColumnGroup>
              <Column title="订单金额" dataIndex="jine" key="jine" align='center' />
              <Column title="买家用户名" dataIndex="userName" key="userName" align='center' />
              <Column title="物流信息" dataIndex="wuLiuInfo" key="wuLiuInfo" align='center' />
              <Column title="售后" dataIndex="orderApply" key="orderApply" align='center'
                render={(text, record) => (
                  <Space size="middle" key='qsd'>
                    {text === 2 && <span className='tuikuan'>请处理退款申请
                    <Button type="primary"
                        onClick={this.tuikuan.bind(this, record)}
                        danger>处理退款</Button></span>}
                  </Space>
                )} />
              <Column title="订单状态"
                dataIndex="danState"
                key="danState"
                align='center'
                render={(text, record) => (
                  <Space size="middle" key='qwerttt'>
                    {text}
                    {/* <span><Link to={{ pathname: '/leinfo', query: { record: record } }}>订单详情</Link></span> */}
                  </Space>
                )}
              />
              <Column
                title="操作"
                key="action"
                align='center'
                render={(text, record) => (
                  <Space size="middle" key='xq'>
                    <span><Link to={{ pathname: '/leinfo', query: { record: record } }}>订单详情</Link></span>
                  </Space>
                )}
              />
            </Table>,
          </div>
        </div>
      </>
    );
  }
}

export default Dingdanliebiao;